package com.gitee.l0km.javadocreader;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.MemberDoc;
import com.sun.tools.javadoc.ClassDocImpl;

@SuppressWarnings("restriction")
public class JavaDocUtils {

	/**
	 * 返回类型的全名字符串
	 * @param type
	 */
	public static String getTypeName(Class<?> type) {
		StringBuilder dimensions = new StringBuilder();
		while (type.isArray()) {
			dimensions.append("[]");
			type = type.getComponentType();
		} 
		String name = type.getName().replaceAll("\\$", "\\.");
		return new StringBuilder(name).append(dimensions).toString();
	}
	/**
	 * 将类型数组转为对应的全名类型字符串数组 
	 * @param parameterTypes
	 */
	private static String[] prepareTypes(Class<?>[] parameterTypes) {
		String[] typeNames = new String[parameterTypes.length];
		for(int i=0;i<typeNames.length;++i) {
			typeNames[i] = getTypeName(parameterTypes[i]);
		}
		return typeNames;
	}
	/**
	 * 在{@link ClassDoc}中查找与 {@link Member} 匹配的{@link MemberDoc}<br>
	 * @param classDoc
	 * @param member  member
	 */	
	public static MemberDoc getMemberDoc(ClassDoc classDoc,Member member) {
		if (null == classDoc || null == member){
			return null;
		}
		ClassDocImpl classDocImpl=(ClassDocImpl)classDoc;
		if(member instanceof Method) {
			return classDocImpl.findMethod(member.getName(),prepareTypes(((Method)member).getParameterTypes()));
		}else if(member instanceof Constructor<?>){
			return classDocImpl.findConstructor(member.getName(),prepareTypes(((Constructor<?>)member).getParameterTypes()));
		}else if(member instanceof Field){
			return classDocImpl.findField(member.getName());
		} else {
			throw new IllegalArgumentException("UNSUPPORTD member type " + member.getClass().getName());
		}
	}
}
